<?php
namespace app\model;

use Elasticsearch\ClientBuilder;

/**
 * ElasticSearch
 * @author 贺强
 * @time   2022/1/18 11:16
 */
class EsModel
{
    /**
     * 获取es对象
     * @author 贺强
     * @time   2022/1/18 11:31
     * @return es对象
     */
    protected static function getEsClient()
    {
        $client = ClientBuilder::create()->setHosts([self::getEsConfig()])
            ->setConnectionPool('\Elasticsearch\ConnectionPool\SimpleConnectionPool', [])
            ->setRetries(10)->build();
        return $client;
    }

    /**
     * 获取es配置
     * @author 贺强
     * @time   2022/1/18 11:30
     * @return 配置
     */
    public static function getEsConfig()
    {
        $config = [
            'host' => '127.0.0.1',
            'port' => '9200',
            'scheme' => 'http',
        ];
        return $config;
    }

    /**
     * 插入数据
     * @author 贺强
     * @time   2022/1/18 11:29
     * @param string $table 表名
     * @param array  $data  要插入的数据
     */
    public static function insert($table, array $data)
    {
        $param = [
            'index' => $table,
            'id' => $data['id'],
            'body' => $data,
        ];
        $client = self::getEsClient();
        $res = $client->index($param);
        return $res;
    }

    /**
     * 插入数据集合
     * @author 贺强
     * @time   2022/1/18 11:33
     * @param array $data 要插入的数据集合
     */
    public static function insertAll(array $data)
    {
        $client = self::getEsClient();
        $res = $client->bulk($data);
        return $res;
    }

    /**
     * 删除 es
     * @author 贺强
     * @time   2022/1/18 11:36
     * @param string $table 表名
     * @param string $id    ID
     */
    public static function delete($table, $id)
    {
        $param = [
            'index' => $table,
            'id' => $id,
        ];
        $client = self::getEsClient();
        $res = $client->delete($param);
        return $res;
    }

    /**
     * 获取 es 数据
     * @author 贺强
     * @time   2022/3/8 14:33
     * @param string es 索引
     * @param array  条件
     * @return array|string
     */
    public static function getData($table, array $condition)
    {
        $param = [
            'scroll' => '1m',
            'size' => 20,
            'index' => $table,
            'body' => [
                'query' => $condition,
                'sort' => ['ctime' => 'desc'],
            ],
        ];
        $client = self::getEsClient();
        try {
            $data = $client->search($param);
            $list = [];
            while (!empty($data['hits']['hits'])) {
                $list[] = $data['hits']['hits'];
                $scroll_id = $data['_scroll_id'];
                $data = $client->scroll([
                    'body' => [
                        'scroll_id' => $scroll_id,
                        'scroll' => '1m',
                    ],
                ]);
            }
        } catch (\Exception $e) {
            return $e->getMessage();
        }
        return $list;
    }
}